package controllers;

import models.Host;
import play.*;
import play.mvc.*;

import views.html.*;
import static play.libs.Json.toJson;

public class Application extends Controller {
  
    public static Result about() {
        return ok(toJson("SoNS Social Machine is running ok!"));
    }
    
    public static Result listHosts() {
        return ok(toJson(Host.all()));
    }
    
    /**
     * Usage example:
     * POST <host>/sons/hosts?name=<name>&desc=<desc>&owner=<owner>&contact=<contact>&path=<path>&pw=<password>
     * Example: http://localhost:9000/sons/hosts?name=filyou&desc=teste da filyou&owner=Kellyton Brito&contact=kellyton.brito@gmail.com&path=localhost:9002&pw=kbritovisk
     * TODO Tratar a exceção que dá se tentar cadastrar mais de uma vez
     * @param name
     * @param desc
     * @param owner
     * @param contact
     * @param path
     * @param pw
     * @return
     */
    public static Result addHost(String name, String desc, String owner, String contact, String path, String pw) {
    	Host host = new Host();
    	host.name = name;
    	host.description = desc;
    	host.owner = owner;
    	host.contact = contact;
    	host.path = path;
    	host.setPassword(pw);
        
    	return ok(toJson(host));
    	
    }
    
	/**
     * Usage example:
     * PUT <host>/sons/hosts?name=<name>&desc=<desc>&owner=<owner>&contact=<contact>&path=<path>&pw=<password>&opw=<oldPassword>
     * Example: http://localhost:9000/sons/hosts/filyou?desc=teste da filyou updating&owner=Kellyton Brito&contact=kellyton.brito@gmail.com&path=localhost:9002&pw=kbritovisk&opw=kbritovisk
     * TODO Tratar quando ele não acha o registrou e quando a senha antiga está errada
     * @param name
     * @param desc
     * @param owner
     * @param contact
     * @param path
     * @param pw
     * @return
     */
    public static Result updateHost(String name, String desc, String owner, String contact, String path, String pw, String opw) {
    	Host host = new Host();
    	host.name = name;
    	host.description = desc;
    	host.owner = owner;
    	host.contact = contact;
    	host.path = path;
    	host.setPassword(pw);
    	
    	Host.update(host, opw);
        
    	return ok(toJson(host)); 	
    }
    
    /**
     * Example: http://localhost:9000/sons/hosts/<username>
     * @param id
     * @return
     */
    public static Result getHost(String id) {
        return ok(toJson(Host.find(id)));
    }
    
    public static Result getPath(String id) {
    	return ok(toJson(Host.find(id).path));
    }
  
}
